<template>
    <div class="app-container">
      <div class="material-top"> 
         <div class="material-title">{{ titleName }}</div>
          <el-button type="primary" color="#fff" @click="goBack"  :icon="ArrowLeft">返回</el-button>
      </div>
      <div class="material-main">
         <div class="material-step">
            <el-steps :active="active" finish-status="success">
                <el-step title="产品基本信息" />
                <el-step title="产品参数配置" />
                <el-step title="申请材料配置" />
                <el-step v-if="true" title="产品发布" />
            </el-steps>
         </div>
         <div class="material-form" v-show="active==0">
         <el-form :model="formData" ref="addProducts" :rules="rules" label-width="120px" >
            <el-row>
                  <el-col :span="22" :offset="1">
                     <div class="form-title">
                        基本信息
                     </div>
                  </el-col>
               </el-row>
            <el-row >
               <el-col :span="12" :offset="2">
                  <el-form-item label=" 产品名称" prop="name"><el-input  :readonly="viewShow" v-model="formData.name" /></el-form-item>
                  <el-form-item label="担保类型" prop="type"> 
                           <el-select  :disabled="viewShow" v-model="formData.type"  placeholder="请选择" >
                                        <el-option
                                        v-for="item in twoArr"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                        />
                                    </el-select>
                  </el-form-item>
                  <el-form-item label="产品封面" prop="topic">
                     <ImageUpload v-model="imageUrls" ></ImageUpload>
                  </el-form-item>
                  <el-form-item label="产品介绍" prop="topic"> <el-input  :readonly="viewShow" rows="5" type="textarea" v-model="formData.topic" /> </el-form-item>
                  <el-form-item label="产品亮点" prop="desc_str"> <el-input :readonly="viewShow" rows="5" type="textarea" v-model="formData.desc_str" /> </el-form-item> 
                  <el-form-item label="产品标签">
                     <el-checkbox-group :disabled="viewShow" v-model="formData.label">
                     <el-checkbox label="新品" name="type" />
                     <el-checkbox label="推荐" name="type" />
                     <el-checkbox label="精品" name="type" />
                     </el-checkbox-group>
                  </el-form-item>
                  <el-form-item label="年利率" prop="year_rate"> <el-input :readonly="viewShow"  v-model="formData.year_rate" /> </el-form-item> 
                  <el-form-item label="日利率" prop="daliy_rate"> <el-input :readonly="viewShow"  v-model="formData.daliy_rate" /> </el-form-item> 
               </el-col>
               </el-row>
               <el-row>
                  <el-col :span="22" :offset="1">
                     <div class="form-title">
                        担保参数
                     </div>
                  </el-col>
               </el-row>
               <el-row>
                  <el-col :span="12" :offset="2">
                  <el-form-item label="放款通道" prop="channel">
                     <el-radio-group  :disabled="viewShow" v-model="formData.channel">
                     <el-radio label="1" >委托银行放款</el-radio>
                     <el-radio label="2" >金融机构放款</el-radio>
                     </el-radio-group>
                  </el-form-item>
                  <el-form-item label="担保额度范围" required>
                     <el-row :gutter="20">
                        <el-col :span="11">
                           <el-form-item prop="base_quota">
                              <el-input
                              :readonly="viewShow"
                              v-model.number="formData.base_quota"
                              label="最低金额"
                              type="number"
                              placeholder="最低金额"
                              oninput="value=value.replace(/^0|[^0-9]/g, '')"
                              />

                           </el-form-item>
                        </el-col>
                        <el-col :span="2">
                           -
                        </el-col>
                        <el-col :span="11">
                        <el-form-item prop="max_quota">
                           <el-input
                           :readonly="viewShow"
                           type="number"
                           v-model.number="formData.max_quota"
                           label="最高金额"
                           placeholder="最高金额"
                           oninput="value=value.replace(/^0|[^0-9]/g, '')"
                           />
                        </el-form-item>
                        </el-col>
                     </el-row>
                     </el-form-item>
                  <el-form-item label="还款方式" prop="method">
                     <el-checkbox-group :disabled="viewShow" v-model="formData.method">
                     <el-checkbox label="1">等额本息</el-checkbox>
                     <el-checkbox label="3">等本等息</el-checkbox>
                     <el-checkbox label="4">先息后本</el-checkbox>
                     <el-checkbox label="5">一次性还息付本</el-checkbox>
                     </el-checkbox-group>
                  </el-form-item>
                  <el-form-item label="担保期限" prop="stages">
                     <el-checkbox-group  :disabled="viewShow" v-model="formData.stages">
                     <el-checkbox v-for="(item,index) in monthList" :key="index" :label="item.id">{{ item.loan_type }}</el-checkbox>
                     </el-checkbox-group>
                  </el-form-item>
               </el-col>
            </el-row>
       </el-form>
       </div>
       <div class="preview-form" v-show="active==1">
         <el-row justify="center">
            <el-col :span="21">
               <div class="form-title">
                        产品参数设置 
                     </div>
                     <el-form-item  label="选择产品参数设置">
                        <el-tree-select
                        v-model="valueSelect"
                        :data="dataSelect"
                        multiple
                        :render-after-expand="false"
                        show-checkbox
                        check-strictly
                        :disabled="viewShow"
                        @change="treeChange"
                     />
                     </el-form-item>
      <div class="replenish-title">
           <div class="title-tag">补充参数说明：</div> 
           <div>授权认证信息、补充资产信息可根据实际产品业务需要设置，设置后用户在申请该产品担保时，可填写更完善的参数。</div>
        </div>
        <div class="form-title"> 产品参数预览</div> 
        <el-tabs
            v-model="activeName"
            type="card"
            class="demo-tabs"
            @tab-click="handleClick"
         >
         <el-tab-pane 
           v-for="(item,index) in tabNames" 
           :key="index" 
           :label="item.name" 
           :name="item.id">
           <Tabpanes 
           v-for="(itm ,inx) in item.list" 
           :key="inx" 
           :personLength="item.list.length"
           :personList="itm"
           :personView="!viewShow"
           />
         </el-tab-pane>
        </el-tabs>
            </el-col>
         </el-row>
       </div>
       <div class="apply-form" v-show="active==2">
         <el-row justify="center">
            <el-col :span="21">
               <div class="form-title"> 产品申请材料</div>
               <p>请设置申请材料</p>
               <el-transfer v-model="formData.materials" :data="dataArr" :titles="['材料列表', '已设置']" />
            </el-col>
            <div>
            <el-checkbox :disabled="viewShow" v-model="formData.materials_must">以上设置的材料，是否要求用户必须提交</el-checkbox>
            </div>
         </el-row>
         </div>
      <div class="product-issue" v-if="active==3">
           <Release :viewShow ='viewShow' v-model='formData.org_id' ></Release>
      </div>
      </div>
       <el-form label-width="100px">
          <div style="text-align: center;margin-left:-120px;margin-top:30px;">
             <el-button type="primary" v-if="active!=0" @click="preStep()">上一步，{{ preText }}</el-button>
             <el-button type="primary" v-if="!viewShow"  @click="nextStep()">下一步， {{nextText}}</el-button>
             <el-button type="primary" v-else-if="active!=3"  @click="nextStep()">下一步， {{nextText}}</el-button>
          </div>
       </el-form>
    </div>
 </template>
 
 <script setup name="AddMaterial">
 import {
  addProduct,
  updateProduct,
  oneProduct,
  uploadProduct,
  queryMonthProduct
} from "@/api/product/product";
import {fileHttpUrl} from "@/api/file"
import {  queryParameter } from "@/api/product/parameter";
 import { ArrowLeft } from  '@element-plus/icons-vue'
 import Tabpanes from'@/components/Tabpanes'
 import Release from'@/components/Release'
 import { nextTick, onActivated, reactive } from 'vue';
 import { listMaterial} from "@/api/product/material"
 const { proxy } = getCurrentInstance();
 const active = ref(0);//进步器
 const route = useRoute();
 const typeOne = ref();
 const titleName = ref('新增担保产品');
 const  oneArr = ref([{ value: "1",label: "个人",} ]);
 const ids = ref('1');
 const viewType = ref('新增');
 const viewShow = ref(true);
 const imageUrls=ref([])
 const valueSelect = ref();
 const activeName = ref('')
 const tabNames = ref([]) 
const dataSelect = ref([])
 const twoArr = ref([
 {
      value:"1",
    label:"个人信用"
  },{
    value:"2",
    label:"个人分期"
    },{
    value:"3",
    label:"个人分期"
    },{
    value:"4",
    label:"个人抵押"
    },{
    value:"5",
    label:"企业信用"
    },{
    value:"6",
    label:"企业分期"
    },{
    value:"7",
    label:"企业租赁"
    }
    ]);
 const isRelease = ref(true)//是否是发布机构
 const  preText = ref('产品基本信息');
 const  nextText = ref('产品参数配置');
 const data = reactive({
   formData:{},
   rules: {
      name:[{ required: true, message: "材料名称不能为空", trigger: "blur" }, { min: 2, max: 20, message: "用户名称长度必须介于 2 和 20 之间", trigger: "blur" }],
      type:[{ required: true, message: "请选择担保类型", trigger: "change" }],
      topic:[{ required: true, message: "产品介绍不能为空", trigger: "blur" }, { min: 2, max: 20, message: "用户名称长度必须介于 2 和 20 之间", trigger: "blur" }],
      base_quota:[{  type: "number",required: true, validator:validateRange('base_quota', 'max_quota', true), trigger: 'blur' }],
      max_quota:[{ type: "number",required: true,validator:validateRange("max_quota","base_quota",false),  trigger:'blur' }],
      channel:[{ required: true, message: "请选择放款通道", trigger: "change" }],
      stages:[{ required: true, message: "请选择担保期限", trigger: "change" }],
      year_rate:[{ type: "number",required: true,validator:rateRegx(),  trigger:'blur' }],
      daliy_rate:[{ type: "number",required: true,validator:rateRegx(),  trigger:'blur' }],
   }
 });
const monthList = ref([])
const {formData,rules} = toRefs(data)
const dataArr = ref([])
function  rateRegx(){
   var regx2= /^(([1-9][0-9]{0,1}[.][0-9]{1,4})|([1-9])|([1-9][0-9]{1})|([0][.][0-9]{1}[1-9]{0,3}))$/;
   return (rule, value, callback) => {
   if(!regx2.test(value)){
      return callback(new Error(`利率只能是数字或小数！最多输入4位小数，且不能超过100%！`))
   }
  }
}
/**担保金额范围校验*/
  function  validateRange(params, compare, flag) {
      const lowLimit = '0'
      const upLimit = '200000'
      return (rule, value, callback) => {
        if (!value || value === '0') {
          return callback(new Error(`请输入大于的0整数`))
        } else if (value) {
          const paramsValue = +formData.value[params]
          const compareValue = +formData.value[compare]
          if (flag) {
            if (paramsValue > compareValue) {
            //   proxy.$refs["addProducts"].clearValidate([compare])
            //   return callback(new Error(`${lowLimit}不能大于${upLimit}`))
              return callback(new Error("最低金额不能大于最高金额"))
            } else {
               proxy.$refs["addProducts"].clearValidate(compare)
              if (!Number(formData.value[compare])) proxy.$refs["addProducts"].validateField(compare)
            }
            callback()
          } else {
            if (paramsValue < compareValue) {
               return callback(new Error("最高金额不能小于于最低金额"))
            //   return callback(new Error(`${upLimit}不能小于${lowLimit}`))
            } else {
              proxy.$refs["addProducts"].clearValidate(compare)
              if (!Number(formData.value[compare])) proxy.$refs["addProducts"].validateField(compare)
            }
            callback()
          }
          callback()
        } else {
          callback()
        }
      }
    }
const value = ref([])

watch(active, () => {
  initHandle();
})
 /** 重置表单 */
 function resetFrom(){
   formData.value = {
      name:undefined,
      type:undefined
   }
 }
 /** 下一步与上一步 */
 function preStep() {
   if(active.value>0){
      active.value--
   }
 };
 function nextStep() {
   if(active.value == 3){
      proxy.$refs["addProducts"].validate(valid => {
           let personal_info ='',auth_info='',supplement_info='';
             if(valueSelect.value.length>0){
              for(let i in tabNames.value){
                 personal_info += tabNames.value[i].id+',';
                 for(let k in tabNames.value[i].list){
                    auth_info += tabNames.value[i].list[k].id+','; 
                  if(localStorage.getItem('id'+tabNames.value[i].list[k].id)){
                    supplement_info+=localStorage.getItem('id'+tabNames.value[i].list[k].id)
                  }
                 }
              }
             }else{
              personal_info ='',auth_info='',supplement_info='';
             }
         if(valid){
            if( !imageUrls.value.length>0 ){
               return  proxy.$modal.msgWarning("请上传产品封面图片");
            } 
               let params = {
               ...formData.value
               }
               params.label = params.label?.toString();
               params.materials = params.materials?','+params.materials.toString()+',':'';
               params.stages = params.stages?.toString();
               params.method = params.method?.toString();
               params.personal_info = personal_info?',' + personal_info:"";
               params.supplement_info = supplement_info?','+ supplement_info:"";
               params.auth_info = auth_info?','+ auth_info:"";
               params.materials_must = params.materials_must?'0':'1';
               params.status = "1";
               params['img_path'] = imageUrls.value.map(item=>item.file_path).join(',');
               if(viewType.value == '新增'){
                  addProduct(params).then(res=>{
                     if( res.code=='200' && res.data ){
                        proxy.$modal.msgSuccess("新增成功"); 
                        goBack()
                     }else{
                        proxy.$modal.msgWarning(res.msg);
                     }   
                     })  
               }else{
                  updateProduct(params).then(res=>{
                     if( res.code=='200' && res.data){
                        proxy.$modal.msgSuccess("修改成功"); 
                     }else{
                        proxy.$modal.msgWarning(res.msg);
                     }
                     }) ;
               }
         }else{
             proxy.$modal.msgWarning("请填写正确信息");
         }
        })
   }
   if(active.value<3){
      active.value ++
   }
};
 /** 返回 */
 function goBack() {
   proxy.$tab.closeOpenPage('product')  
 };
function initHandle(){
   if(active.value == 0){
      nextText.value ='产品参数配置';
   }else if(active.value == 1){
      preText.value = '产品基本信息';
      nextText.value ='申请材料配置';
   }else if(active.value == 2){
      preText.value = '产品参数配置';
      nextText.value ='产品发布';
   }else{
      preText.value = '申请材料配置';
      nextText.value ='完成,提交发布';
   };
}
/**获取担保分期*/
 function queryMonth(){
   queryMonthProduct({
      "page_size": 1,
		"page_count": 30
   }).then(res=>{
      monthList.value = res.data.list;
      ids.value = route.query.ids;
      viewType.value = route.query.viewType;
      if( viewType.value == '新增'){
         titleName.value ='新增担保产品';
         viewShow.value = false;
         getParamterInfo('')
         getLoanMaterials(false);
      }else if( viewType.value == '查看'){
         titleName.value ='查看担保产品';
         viewShow.value = true;
         getInfoProduct()
         getLoanMaterials(true);
      }else{
         titleName.value ='编辑担保产品'
         getInfoProduct();
         viewShow.value = false;
         getLoanMaterials(false);
      };
     
   })
   let dd = localStorage.getItem('authority')
   localStorage.clear();
   localStorage.setItem('authority',dd)
 }
 /**查看详情*/
 function getInfoProduct(){
   oneProduct(ids.value).then(res=>{
      let dataList = res.data;
            dataList.label = res.data.label?.split(',');
            dataList.stages = res.data.stages?.split(',');
            dataList.materials_must = res.data.materials_must=='0'?true:false;
            dataList.channel =res.data.channel?.toString();
            dataList.type =res.data.type?.toString();
            dataList.method = res.data.method?.toString()?.split(',');
            dataList.org_id =res.data.org_id?.toString()?.split(',');
            dataList.stages = dataList.stages?.map( item =>{
                  item= Number(item)
                  return item;
               })
               dataList.status =res.data.status
          dataList.materials = res.data.materials?.slice(1,res.data.materials.length-1).split(',')
         formData.value = dataList;
         getImges(res.data.img_path);
        getParamterInfo(res.data);
   })
 }
 /**获取图片信息*/
 function getImges(vl){
   if(vl){
      let arrr = vl.split(',');
      for(let a in arrr){
         if(arrr[a]){
            fileHttpUrl({file_path:arrr[a]}).then(res=>{
               console.log(res)
               imageUrls.value.push({
                  name: res.data[0].file_name,
                   file_path: res.data[0].file_path,
                 url: "http://" + res.data[0].http_url,
               })
            }) 
         }
      }
   }
 }
  /**参数选择*/
  function treeChange(vl){
   //预览展示
   tabNames.value=[] 
   setTimeout(()=>{
      if(valueSelect.value.length>0){
         tabNames.value =dataSelect.value.filter(item=>{
            return valueSelect.value.indexOf(item.id)!=-1
         })
         if(tabNames.value?.length>0){
            activeName.value = tabNames.value[0].id
         }else{
            activeName.value = ''
         }
      }else{
         tabNames.value=[] 
      }
   },200)
}
 /**预览切换*/
 function handleClick(){

 }

 /**获取参数配置信息*/
 function getParamterInfo(vl){
   queryParameter().then(res=>{
      let treeArr =[]
      res.data.forEach(item=>{
          item.value = item.id;
          item.label = item.name;
          if(item.list?.length>0){
            item.children= item.list.map(itm=>{
               itm.value = itm.id;
               itm.label = itm.name;
               return itm
            })
          }
          treeArr.push(item)
         return
      }) 
      dataSelect.value = treeArr;
      if(vl!=''){
         valueSelect.value = vl.personal_info?.slice(1,vl.personal_info.length-1).split(',').map(item=>{
            return Number(item);
         })
         treeChange()
      }
   });
 }
 /**获取担保材料信息*/
 function getLoanMaterials(vl){
   dataArr.value = []
   listMaterial({
      page_size:1,
      page_count:100
   }).then(res=>{
   if(res.data.total_page>0){
    //先筛选出启用状态
     res.data.list.forEach(item=>{
      if( item.status == 1 ){
         dataArr.value.push({
          key:item.id.toString(),
          label:item.name,
           disabled:vl})
      }
    })
   }else{
      dataArr.value = []
   }
   
  });
 }
 onActivated(()=>{
    queryMonth();
 })
 </script>
 <style lang="scss" scoped>
 .material-title{
   font-size:15px;
   font-weight: bold; 
 }
.material-top{
    display: flex;
    justify-content: space-between;
    border-bottom:1px solid #ddd;
}
.replenish-title{
    background-color: rgba(255, 204, 153, 1);
    line-height: 20px;
    padding: 20px 14px;
}
.title-tag{
    font-weight: bold;
}
.material-step{
   margin: 20px 60px;
}
.material-main{
   width:90%;
   // background-color: #bfbfbf;
 
}
.material-form{
   margin: 20px;
   background-color: #fff;
   padding-bottom: 40px;
}
.apply-form{
   background: #fff;
}
.apply-state{
   background-color: rgba(255, 204, 153, 1);
   // font-size: 14px;
   padding-left:20px ;
   line-height: 42px;
}
.productImg{
   font-weight: bold;
   font-size: 14px;
   color: #606266;
   width: 120px;
   padding-right: 10px;
   text-align: right;
}
.form-title{
   background-color:#a2a6ac ;
   line-height: 52px;
   padding-left: 20px;
   font-size: 18px;
   color:#fff;
   margin-bottom: 20px;
}
</style>
 